package com.webchat.connect.messagequeue.consumer.service;


import com.webchat.common.constants.ConnectConstants;
import com.webchat.common.util.JsonUtil;
import com.webchat.connect.websocket.handler.GroupVideoWebSocketEndPointServletHandler;
import com.webchat.connect.websocket.handler.P2PVideoWebSocketEndPointServletHandler;
import com.webchat.domain.vo.request.mess.VideoChatMessageRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Set;

@Slf4j
@Service
public class WebRtcSDPConsumeService {


    public void consume(String message) {

        log.info("音视频信令消息消费 =====> message:{}", message);
        VideoChatMessageRequestVO chatMessage = JsonUtil.fromJson(message, VideoChatMessageRequestVO.class);
        if (chatMessage == null) {
            return;
        }
        // 如果是来自P2P一对一音视频信令广播消息：groupId为空，只有群聊视频视频场景下groupId有值
        String groupId = chatMessage.getGroupId();
        String receiverId = chatMessage.getTargetUserId();
        // 校验用户ws 连接session是否在当前机器Hash表P2PVideoWebSocketEndPointServletHandler
        Set<String> bizCodes = ConnectConstants.ConnectBiz.getBizCode(ConnectConstants.BizEnum.CHAT);
        for (String bizCode: bizCodes) {
            WebSocketSession session = this.getSession(bizCode, groupId, receiverId);
            if (session == null || !session.isOpen()) {
                continue;
            }
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("音视频信令消息推送异常！", e);
            }
        }
    }

    private WebSocketSession getSession(String bizCode, String groupId, String userId) {
        if (StringUtils.isNotBlank(groupId)) {
            return GroupVideoWebSocketEndPointServletHandler.getSession(bizCode, groupId, userId);
        }
        return P2PVideoWebSocketEndPointServletHandler.getSession(bizCode, userId);
    }
}
